package student.thread.futureTask;

import cn.hutool.core.lang.Console;

import java.util.concurrent.*;

public class FutureTaskDemo {

    private static final ConcurrentMap<Object, Future<String>> taskCache = new ConcurrentHashMap<>();

    private static String executionTask(final String taskName) throws ExecutionException, InterruptedException {
        while (true) {
            // 1.1,2.1
            Future<String> future = taskCache.get(taskName);
            if (future == null) {
                Callable<String> task = () -> taskName;
                FutureTask<String> futureTask = new FutureTask<>(task);
                // 1.3
                future = taskCache.putIfAbsent(taskName, futureTask);
                if (future == null) {
                    future = futureTask;
                    // 1.4执行任务
                    futureTask.run();
                }
            }
            try {
                // 1.5
                return future.get();
            } catch (CancellationException e) {
                taskCache.remove(taskName, future);
            }
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String res = executionTask("fsdf");
        Console.log("FutureTask return v：" + res);
    }
}
